package com.jh.user.service;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import com.jh.user.business.*;
import com.jh.user.pojo.Brand;
import com.jh.user.pojo.InfoUser;
import com.jh.user.pojo.User;
import com.jh.user.pojo.UserBankInfo;
import com.jh.user.util.CommonsUtil;
import com.jh.user.util.HttpUtils;
import com.jh.user.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class UserRealnameAuthService {


    private static final Logger LOG = LoggerFactory.getLogger(UserRealnameAuthService.class);

    @Value("${user.realname.uploadpath}")
    private String realnamePic;

    @Value("${user.realname.downloadpath}")
    private String downloadPath;

    @Autowired
    private UserBankInfoBusiness userBankInfoBusiness;

    @Autowired
    private UserLoginRegisterBusiness userLoginRegisterBusiness;

    @Autowired
    private UserCoinBusiness userCoinBusiness;

    @Autowired
    private BrandManageBusiness brandManageBusiness;

    @Autowired
    private RealNameAuthPhotoBusiness realNameAuthPhotoBusiness;


    @Autowired
    Util util;

    /**
     * 读取用户的文件
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/download/realname")
    public @ResponseBody
    Object downloadUserPic(HttpServletRequest request,
                           @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                           @RequestParam(value = "phone") String phone
    ) {
        Map<String, Object> map = new HashMap<>();
        try {
            long brandId;
            User user;
            Brand brand = null;
            try {
                brandId = Long.valueOf(sbrandId);
            } catch (NumberFormatException e) {
                brandId = -1;
            }
            if (brandId == -1) {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            } else {
                brand = brandManageBusiness.findBrandById(brandId);
                if ("6".equals(brand.getBrandType())) {
                    user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
                } else {
                    user = userLoginRegisterBusiness.queryUserByPhone(phone);
                }
            }
            if (user == null) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }
            /* 获取身份证实名信息*/
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            String url = uri.toString() + "/v1.0/paymentchannel/realname/userid";
            MultiValueMap<String, Long> requestEntity = new LinkedMultiValueMap<>();
            requestEntity.add("userid", user.getId());

            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.postForObject(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.fromObject(result);
            JSONObject authObject = jsonObject.getJSONObject("realname");
            InfoUser infouser = new InfoUser();

            //系统编号
            infouser.setUserid(user.getId());
            //贴牌号
            infouser.setBrandId(user.getBrandId());
            //贴牌名称
            infouser.setBrandName(user.getBrandname());
            //用户手机号
            infouser.setPhone(user.getPhone());

            //真是姓名
            infouser.setRealname(authObject.getString("realname"));
            //身份证号
            infouser.setIdcard(authObject.getString("idcard"));
            UserBankInfo ubi = userBankInfoBusiness.queryDefUserBankInfoByUserid(user.getId());

            if (ubi != null) {

                //银行卡名称
                infouser.setBankName(ubi.getBankName());
                //银行卡号
                infouser.setCardNo(ubi.getCardNo());

            } else {
                //银行卡名称
                infouser.setBankName(null);
                //银行卡号
                infouser.setCardNo(null);
            }

            //用户性别
            infouser.setSex(user.getSex());

            //实名状态
            infouser.setRealnameStatus(user.getRealnameStatus());
            //级别
            infouser.setGrade(user.getGrade());
            //注册时间
            infouser.setCreateTime(user.getCreateTime());
    //        List<String> filepaths = new ArrayList<String>();
    //        if (brand != null && "6".equals(brand.getBrandType())) {
    //            File file = new File(realnamePic + brandId + File.separator + phone);
    //            String[] filelist = file.list();
    //            if (filelist != null) {
    //                for (int i = 0; i < filelist.length; i++) {
    //                    filepaths.add(downloadPath + brandId + File.separator + phone + File.separator + filelist[i]);
    //                }
    //            }
    //        } else {
    //            File file = new File(realnamePic + File.separator + phone);
    //            String[] filelist = file.list();
    //            if (filelist != null) {
    //                for (int i = 0; i < filelist.length; i++) {
    //                    filepaths.add(downloadPath + phone + File.separator + filelist[i]);
    //                }
    //            }
    //        }

            Map<String, String> res = realNameAuthPhotoBusiness.findPhotoListByUserId(user.getId());

            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESULT, res);
            map.put("infouser", infouser);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
        return map;
    }


    /**
     * 更新实名认证的状态--小磊
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/users/updatestatus/status")
    public @ResponseBody
    Object updatesRealnameStatus(HttpServletRequest request,
                                 @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                                 @RequestParam(value = "phone") String phone,
                                 @RequestParam(value = "status") String status
    ) {

        Map<String, Object> map = new HashMap<>();
        long brandId = -1;
        User user;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            if ("6".equals(brandManageBusiness.findBrandById(brandId).getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
            } else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }

        user.setRealnameStatus(status);
        //调用实名注册接口，将真实姓名存入用户表
        if (status.equals("1")) {
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            //取出姓名
            String url = uri.toString() + "/v1.0/paymentchannel/realname/userid";
            MultiValueMap<String, Long> requestEntity = new LinkedMultiValueMap<String, Long>();
            requestEntity.add("userid", user.getId());

            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.postForObject(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.fromObject(result);

            JSONObject authObject = jsonObject.getJSONObject("realname");

            user.setFullname(authObject.getString("realname"));
        }
        user = userLoginRegisterBusiness.saveUser(user);
        if (status.equals("1")) {
            User preuser = userLoginRegisterBusiness.queryUserById(user.getPreUserId());
            preuser.setEncourageNum(preuser.getEncourageNum() + 1);
            userLoginRegisterBusiness.saveUser(preuser);
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        return map;
    }

    /**
     * 更新用户的状态
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/updatestatus/status")
    public @ResponseBody
    Object updateRealnameStatus(HttpServletRequest request,
                                @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                                @RequestParam(value = "phone") String phone,
                                @RequestParam(value = "status") String status    //1通过审核，2拒绝通过
    ) {

        Map<String, Object> map = new HashMap<>();
        long brandId;
        User user;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            if ("6".equals(brandManageBusiness.findBrandById(brandId).getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
            } else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }

        user.setRealnameStatus(status);
        //调用实名注册接口，将真实姓名存入用户表
        if (status.equals("1")) {
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            String url = uri.toString() + "/v1.0/paymentchannel/realname/userid";
            MultiValueMap<String, Long> requestEntity = new LinkedMultiValueMap<>();
            requestEntity.add("userid", user.getId());

            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.postForObject(url, requestEntity, String.class);
            JSONObject jsonObject = JSONObject.fromObject(result);
            JSONObject authObject = jsonObject.getJSONObject("realname");

            user.setFullname(authObject.getString("realname"));
        }
        try {
            user = userLoginRegisterBusiness.saveUser(user);
        } catch (Exception e) {
            LOG.info("=====userid:" + user.getId() + "=====saveUser错误信息：" + e);
            return CommonsUtil.returnError("更新实名认证状态失败");
        }


        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        /*
         * 推送信息URL：/v1.0/user/jpush/tset
         */
//        String alert = "实名认证提示";
//        String content = "亲爱的会员，实名认证已通过审核";
//        // 1表示审核通过  2表示审核拒绝
//        if (status.equals("2")) {
//            content = "亲爱的会员，实名认证审核失败";
//        }
//        String btype = "realnameStatus";
//        String btypeval = status;
//
//        /* 获取身份证实名信息*/
//        URI uri = util.getServiceUrl("user", "error url request!");
//        String url = uri.toString() + "/v1.0/user/jpush/test";
//        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
//        requestEntity.add("userId", user.getId() + "");
//        requestEntity.add("alert", alert + "");
//        requestEntity.add("content", content + "");
//        requestEntity.add("btype", btype + "");
//        requestEntity.add("btypeval", btypeval + "");
//        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.postForObject(url, requestEntity, String.class);
        return map;
    }


    /**
     * 上传 用户的照片（前端调用）
     *
     * @throws
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/upload/realname")
    public @ResponseBody
    Object uploadUserPic(MultipartFile idCardPhoto,
                         MultipartFile idCardBankPhoto,
                         MultipartFile personPhoto,
                         @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                         @RequestParam(value = "phone") String phone) {

        LOG.info("=====进入上传用户照片");

        Map<String, Object> map = new HashMap<>();
        long brandId = -1;
        User user;
        Brand brand = null;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e1) {
            brandId = -1;
        }
        try {
            if (brandId == -1) {
                user = userLoginRegisterBusiness.queryUserByPhone(phone); // 如果brandid=-1通过手机号查询到用户
            } else {
                brand = brandManageBusiness.findBrandById(brandId); // 如果brandid!=-1通过贴牌id找到贴牌
                if ("6".equals(brand.getBrandType())) { // 如果贴牌类型=6
                    user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId); // 通过手机号和贴牌id找到user
                } else {
                    user = userLoginRegisterBusiness.queryUserByPhone(phone); // 如果贴牌类型!=6
                    // 通过手机号找到user
                }
            }

    //        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    //        List<MultipartFile> files = multipartRequest.getFiles("image");
    //
    //        if (brand != null && "6".equals(brand.getBrandType())) {
    //            File dir = new File(realnamePic + brandId + File.separator + phone);
    //            // 创建目录
    //            if (dir.mkdirs()) {
    //                LOG.info("=====创建目录" + realnamePic + brandId + File.separator + phone + "成功");
    //            } else {
    //
    //                File[] tempfiles = dir.listFiles();
    //                for (File file : tempfiles) {
    //                    file.delete();
    //                }
    //
    //                LOG.info("=====创建目录" + realnamePic + brandId + File.separator + phone + "失败");
    //            }
    //
    //            if (files != null && files.size() > 0) {
    //
    //                for (MultipartFile file : files) {
    //
    //                    String fileName = file.getOriginalFilename();
    //
    //                    LOG.info("=====文件名字：" + fileName);
    //                    int suffixIndex = fileName.lastIndexOf(".");
    //                    String suffixName = fileName.substring(suffixIndex);    //后缀名
    //                    if (!"jpg".equals(suffixName)) {
    //                        suffixName = suffixName.substring(0, suffixIndex) + ".jpg";
    //                        LOG.info("=====修改后文件名字：" + fileName);
    //                    }
    //
    //                    File dest = new File(realnamePic + brandId + File.separator + phone + File.separator + fileName);
    //                    try {
    //                        file.transferTo(dest);
    //                    } catch (IllegalStateException e) {
    //                        e.printStackTrace();
    //                    } catch (IOException e) {
    //                        e.printStackTrace();
    //                    }
    //                }
    //            }
    //        } else {
    //            File dir = new File(realnamePic + phone);
    //            // 创建目录
    //            if (dir.mkdirs()) {
    //                //System.out.println("创建目录" + realnamePic + "/" + phone + "成功！");
    //                LOG.info("=====创建目录" + realnamePic + phone + "成功");
    //            } else {
    //
    //                File[] tempfiles = dir.listFiles();
    //                for (File file : tempfiles) {
    //                    file.delete();
    //                }
    //
    //                //System.out.println("创建目录" + realnamePic + "/" + phone + "失败！");
    //                LOG.info("=====创建目录" + realnamePic + phone + "失败");
    //            }
    //
    //            if (files != null && files.size() > 0) {
    //                for (MultipartFile file : files) {
    //
    //                    String fileName = file.getOriginalFilename();
    //                    int suffixIndex = fileName.lastIndexOf(".");
    //                    String suffixName = fileName.substring(suffixIndex);    //后缀名
    //                    LOG.info("=====文件名字：" + fileName + "=====suffixIndex:" + suffixIndex + "=====sufffixName:" + suffixName);
    //                    if (!".jpg".equals(suffixName)) {
    //                        fileName = fileName.substring(0, suffixIndex) + ".jpg";
    //                        LOG.info("=====修改后文件名字：" + fileName);
    //                    }
    //
    //                    File dest = new File(realnamePic + phone + File.separator + fileName);
    //
    //                    try {
    //                        file.transferTo(dest);
    //                    } catch (IllegalStateException e) {
    //                        LOG.info("=====userid:" + user.getId() + "=====错误信息：" + e);
    //                        e.printStackTrace();
    //                    } catch (IOException e) {
    //                        e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }

            realNameAuthPhotoBusiness.uploadRealNameAuthPhoto(idCardPhoto, idCardBankPhoto, personPhoto, user);
//            user.setRealnameStatus("0");
//            userLoginRegisterBusiness.saveUser(user);

            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");

            /*
             * 推送消息 /v1.0/user/jpush/tset
             */
    //        String alert = "实名认证提示";
    //        String content = "亲爱的会员，实名认证正在审核中....";
    //        String btype = "realnameStatus";
    //        String btypeval = "0";
    //
    //        /* 获取身份证实名信息 */
    //        URI uri = util.getServiceUrl("user", "error url request!");
    //
    //        String url = uri.toString() + "/v1.0/user/jpush/test";
    //        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
    //        requestEntity.add("userId", user.getId() + "");
    //        requestEntity.add("alert", alert + "");
    //        requestEntity.add("content", content + "");
    //        requestEntity.add("btype", btype + "");
    //        requestEntity.add("btypeval", btypeval + "");
    //        RestTemplate restTemplate = new RestTemplate();
    //        String result = restTemplate.postForObject(url, requestEntity, String.class);

        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
        return map;
    }

    /**
     * 小磊
     * 上传用户的照片
     *
     * @throws
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/upload/realnames")
    public @ResponseBody
    Object uploadUserPics(HttpServletRequest request,
                          @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                          @RequestParam(value = "phone") String phone) {
        int i = 0;
        Map<String, Object> map = new HashMap<>();
        long brandId = -1;
        User user;
        Brand brand = null;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e1) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone); // 如果brandid=-1通过手机号查询到用户
        } else {
            brand = brandManageBusiness.findBrandById(brandId); // 如果brandid!=-1通过贴牌id找到贴牌
            if ("6".equals(brand.getBrandType())) { // 如果贴牌类型=6
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId); // 通过手机号和贴牌id找到user
            } else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone); // 如果贴牌类型!=6
                // 通过手机号找到user
            }
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("image");

        if (brand != null && "6".equals(brand.getBrandType())) {
            File dir = new File(realnamePic + "/" + brandId + "/" + phone);
            // 创建目录
            if (dir.mkdirs()) {
                System.out.println("创建目录" + realnamePic + "/" + brandId + "/" + phone + "成功！");

            } else {

                File[] tempfiles = dir.listFiles();
                for (File file : tempfiles) {
                    file.delete();
                }

                System.out.println("创建目录" + realnamePic + "/" + brandId + "/" + phone + "失败！");
            }

            if (files != null && files.size() > 0) {
                for (MultipartFile file : files) {
                    int i1 = i++;
                    String fileName = file.getOriginalFilename();
                    StringBuffer stringBuffer = new StringBuffer(fileName);
                    StringBuffer name = stringBuffer.insert(0, i1);
                    File dest = new File(realnamePic + "/" + brandId + "/" + phone + "/" + name);
                    try {
                        file.transferTo(dest);
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            File dir = new File(realnamePic + "/" + phone);
            // 创建目录
            if (dir.mkdirs()) {
                System.out.println("创建目录" + realnamePic + "/" + phone + "成功！");

            } else {

                File[] tempfiles = dir.listFiles();
                for (File file : tempfiles) {
                    file.delete();
                }

                System.out.println("创建目录" + realnamePic + "/" + phone + "失败！");
            }

            if (files != null && files.size() > 0) {

                for (MultipartFile file : files) {
                    int i1 = i++;
                    String fileName = file.getOriginalFilename();
                    StringBuffer stringBuffer = new StringBuffer(fileName);
                    StringBuffer name = stringBuffer.insert(0, i1);
                    File dest = new File(realnamePic + "/" + phone + "/" + name);

                    try {
                        file.transferTo(dest);
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }


    // 实名认证
    @RequestMapping(method = RequestMethod.POST, value = "v1.0/user/upload/realname/user/upload/realname/idCard")
    public @ResponseBody
    Object realnameCertification(HttpServletRequest request,
                                 @RequestParam(value = "brandId", required = false, defaultValue = "-1") String brandIds,
                                 @RequestParam(value = "picNum") String picNum, @RequestParam(value = "phone") String phone,
                                 @RequestParam(value = "userId") long userId) {
        long brandid = Long.valueOf(brandIds);
        Map resultMap = new HashMap();
        User user;
        Brand brand = null;
        if (brandid == -1) {
            user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
        } else {
            brand = brandManageBusiness.findBrandById(brandid);
            if ("6".equals(brand.getBrandType())) {
                user = userLoginRegisterBusiness.findUserByIdAndBrandId(userId, brandid);
            } else {
                user = userLoginRegisterBusiness.queryUserById(userId);
            }
        }

        //判断用户的实名状态
        String status = userLoginRegisterBusiness.findStatusByUserId(userId);
        if (status.equals("0") || status.equals("1")) {
            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            resultMap.put(CommonConstants.RESP_MESSAGE, "请勿重复实名");
        } else {

            if (status.equals("2") || status.equals("3")) {
                List<UserBankInfo> bankInfos = userBankInfoBusiness.queryUserBankInfoByUserid(userId);
                if (bankInfos != null) {
                    userBankInfoBusiness.updateBankCardByUserId(userId);
                }
            }
            MultipartHttpServletRequest multipartRequest;
            List<MultipartFile> files = null;
            try {
                multipartRequest = (MultipartHttpServletRequest) request;
                files = multipartRequest.getFiles("image");
            } catch (Exception e1) {
                LOG.info(e1.getMessage());
            }

            if (brand != null && "6".equals(brand.getBrandType())) {
                File dir = new File(realnamePic + "/" + brandid + "/" + phone);
                // 创建目录
                if (dir.mkdirs()) {
                    System.out.println("创建目录" + realnamePic + "/" + brandid + "/" + phone + "成功！");

                } else {

                    File[] tempfiles = dir.listFiles();
                    for (File file : tempfiles) {
                        // file.delete();
                    }

                    System.out.println("创建目录" + realnamePic + "/" + brandid + "/" + phone + "失败！");
                }

                if (files != null && files.size() > 0) {
                    for (MultipartFile file : files) {

                        String fileName = file.getOriginalFilename();

                        File dest = new File(realnamePic + "/" + brandid + "/" + phone + "/" + fileName);
                        try {
                            file.transferTo(dest);
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                File dir = new File(realnamePic + "/" + phone);
                // 创建目录
                if (dir.mkdirs()) {
                    System.out.println("创建目录" + realnamePic + "/" + phone + "成功！");

                } else {

                    File[] tempfiles = dir.listFiles();
                    for (File file : tempfiles) {
                        // file.delete();
                    }

                    System.out.println("创建目录" + realnamePic + "/" + phone + "失败！");
                }

            }

            String host = "https://dm-51.data.aliyun.com";
            String path = "/rest/160601/ocr/ocr_idcard.json";
            String method = "POST";
            String appcode = "a5d1104a6f73467f85a372562ea69d55";
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "APPCODE " + appcode);
            headers.put("Content-Type", "application/json; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            boolean flag = false;

            Map<String, String> map = new HashMap<String, String>();
            if (picNum.equals("0")) {
                // 对正面图片进行base64编码
                String faceimgBase64 = "";
                try {
                    MultipartFile fileFace = files.get(0);
                    byte[] content = files.get(0).getBytes();

                    faceimgBase64 = new String(Base64.encodeBase64(content));
                } catch (IOException e1) {
                    LOG.error(e1.getMessage());
                }

                String bodys = "{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":" + "\"" + faceimgBase64 + "\""
                        + "}," + "\"configure\":{\"dataType\":50,\"dataValue\":\"{\\\"side\\\":\\\"face\\\"}\"}}]}";
                HttpResponse response;
                try {
                    response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                    LOG.info("=====================身份证正面验证状态====================="
                            + response.getStatusLine().getStatusCode());
                    if (response.getStatusLine().getStatusCode() == 200) {
                        System.out.println(response.toString());
                        String str = EntityUtils.toString(response.getEntity());
                        JSONObject jsonObject = JSONObject.fromObject(str);
                        String resultobj = jsonObject.getString("outputs");
                        JSONArray jsonArray = JSONArray.fromObject(resultobj);

                        String output = jsonArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串
                        JSONObject out = JSONObject.fromObject(output);
                        String address = out.getString("address");
                        String realname = out.getString("name");
                        String idCard = out.getString("num");
                        String birth = out.getString("birth");
                        map.put("name", realname);
                        map.put("address", address);
                        map.put("idCard", idCard);
                        map.put("birth", birth);

                        Date date = new Date();

                        // 获取年
                        int oldYear = Integer.parseInt(birth.substring(0, 4));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                        int toYear = Integer.parseInt(sdf.format(date));
                        int yearPro = toYear - oldYear;

                        // 月
                        sdf = new SimpleDateFormat("MM");
                        int oldMonth = Integer.parseInt(birth.substring(4, 6));
                        int toMonth = Integer.parseInt(sdf.format(date));
                        int monthPro = toMonth - oldMonth;

                        // 获取日
                        sdf = new SimpleDateFormat("dd");
                        int oldDay = Integer.parseInt(birth.substring(6, 8));
                        int toDay = Integer.parseInt(sdf.format(date));
                        int dayPro = toDay - oldDay;

                        // 如果年龄大于18直接通过
                        if (yearPro < 18) {
                            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                            resultMap.put(CommonConstants.RESP_MESSAGE, "未满18周岁");
                        } else if (yearPro == 18 && monthPro < 0) {
                            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                            resultMap.put(CommonConstants.RESP_MESSAGE, "未满18周岁");
                        } else if (yearPro == 18 && monthPro == 0 && dayPro < 0) {
                            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                            resultMap.put(CommonConstants.RESP_MESSAGE, "未满18周岁");
                        } else {
                            /** 将实名信息添加到表中 */
                            // String result = "1";
                            String message = "匹配";
                            RestTemplate restTemplate = new RestTemplate();
                            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
                            String url = uri.toString() + "/v1.0/paymentchannel/realname/add/realname";
                            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                            requestEntity.add("userId", userId + "");
                            requestEntity.add("realname", realname + "");
                            requestEntity.add("idCard", idCard + "");
                            requestEntity.add("message", message + "");
                            String faceResult = restTemplate.postForObject(url, requestEntity, String.class);
                            JSONObject fs = JSONObject.fromObject(faceResult);
                            System.out.println(fs.getString("resp_code"));
                            if (fs.getString("resp_code").equals("000000")) {
                                resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                                resultMap.put("faceMsg", map);
                                resultMap.put(CommonConstants.RESP_MESSAGE, "成功");
                                flag = true;
                            } else if (fs.getString("resp_code").equals("999999")) {
                                resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                                resultMap.put("faceMsg", map);
                                resultMap.put(CommonConstants.RESP_MESSAGE, "请不要重复上传图片");
                                flag = false;
                            }
                        }
                    } else {
                        resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                        resultMap.put(CommonConstants.RESP_MESSAGE, "审核失败");
                        LOG.info("=====================身份证正面审核错误" + response.getStatusLine().getStatusCode()
                                + "========================");
                    }
                } catch (Exception e) {
                    LOG.info(e.getMessage());
                }

            }

            if (picNum.equals("1")) {

                // 对反面图片进行base64编码
                String backimgBase64 = "";
                try {
                    byte[] content = files.get(0).getBytes();
                    backimgBase64 = new String(Base64.encodeBase64(content));
                    String bodys2 = "{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":" + "\"" + backimgBase64 + "\""
                            + "}," + "\"configure\":{\"dataType\":50,\"dataValue\":\"{\\\"side\\\":\\\"back\\\"}\"}}]}";

                    HttpResponse responseBk = HttpUtils.doPost(host, path, method, headers, querys, bodys2);
                    LOG.info("=====================身份证反面验证状态====================="
                            + responseBk.getStatusLine().getStatusCode());
                    JSONObject backJson = null;
                    if (responseBk.getStatusLine().getStatusCode() == 200) {
                        flag = true;
                        String str = EntityUtils.toString(responseBk.getEntity());
                        JSONObject jsonObject = JSONObject.fromObject(str);
                        String resultobj = jsonObject.getString("outputs");
                        JSONArray jsonArray = JSONArray.fromObject(resultobj);

                        String output = jsonArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串
                        JSONObject out = JSONObject.fromObject(output);
                        String startDate = out.getString("start_date");
                        String endDate = out.getString("end_date");
                        String issue = out.getString("issue");
                        map.put("startDate", startDate);
                        map.put("endDate", endDate);
                        map.put("issue", issue);
                        Date date = new Date();
                        // 获取年
                        int oldYear = Integer.parseInt(endDate.substring(0, 4));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                        int toYear = Integer.parseInt(sdf.format(date));
                        int yearPro = oldYear - toYear;

                        // 月
                        sdf = new SimpleDateFormat("MM");
                        int oldMonth = Integer.parseInt(endDate.substring(4, 6));
                        int toMonth = Integer.parseInt(sdf.format(date));
                        int monthPro = oldMonth - toMonth;

                        // 获取日
                        sdf = new SimpleDateFormat("dd");
                        int oldDay = Integer.parseInt(endDate.substring(6, 8));
                        int toDay = Integer.parseInt(sdf.format(date));
                        int dayPro = oldDay - toDay;

                        RestTemplate restTemplate = new RestTemplate();
                        URI uri = util.getServiceUrl("paymentchannel", "error url request!");
                        String url = uri.toString() + "/v1.0/paymentchannel/realname/update/realname";
                        String result = "1";
                        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                        requestEntity.add("userId", userId + "");
                        requestEntity.add("result", result + "");

                        if (yearPro < 0) {
                            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                            resultMap.put("backMsg", map);
                            resultMap.put(CommonConstants.RESP_MESSAGE, "身份证已过有效期");

                        } else if (yearPro == 0 && monthPro < 0) {
                            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                            resultMap.put("backMsg", map);
                            resultMap.put(CommonConstants.RESP_MESSAGE, "身份证已过有效期");

                        } else if (yearPro == 0 && monthPro == 0 && dayPro < 0) {
                            resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                            resultMap.put("backMsg", map);
                            resultMap.put(CommonConstants.RESP_MESSAGE, "身份证已过有效期");

                        } else {
                            String paymentResult = restTemplate.postForObject(url, requestEntity, String.class);
                            backJson = JSONObject.fromObject(paymentResult);
                            if (backJson.getString("resp_code").equals("000000")) {
                                userLoginRegisterBusiness.updateUserStatusByUserId(userId);
                                ;
                                resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                                resultMap.put("backMsg", map);
                                resultMap.put(CommonConstants.RESP_MESSAGE, "成功");

                            } else if (backJson.getString("resp_code").equals("999999")) {
                                resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                                resultMap.put(CommonConstants.RESP_MESSAGE, "请先上传正面照片");
                                flag = false;
                            }
                        }
                    } else {
                        resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                        resultMap.put(CommonConstants.RESP_MESSAGE, "审核失败");
                        LOG.info("=====================身份证正面审核错误" + responseBk.getStatusLine().getStatusCode()
                                + "========================");
                    }
                } catch (IOException e1) {
                    LOG.error(e1.getMessage());
                } catch (Exception e) {
                    LOG.error(e.getMessage());
                }
            }

            // 将图片保存在服务器中
            if (flag) {
                if (files != null && files.size() > 0) {
                    for (MultipartFile file : files) {

                        String fileName = file.getOriginalFilename();

                        File dest = new File(realnamePic + "/" + phone + "/" + fileName);

                        try {
                            file.transferTo(dest);
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }

        }

        return resultMap;
    }


    //根据brandid和status获取一定时间段内的信息
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/query/querynamebystatus")
    public Object queryFullNameByStatus(HttpServletRequest request,
                                        @RequestParam(value = "brand_id", defaultValue = "0", required = false) long brandId,
                                        @RequestParam(value = "realnameStatus", defaultValue = "0,1,2,3", required = false) ArrayList<String> status,
                                        @RequestParam(value = "start_time", required = false) String startTime,
                                        @RequestParam(value = "end_time", required = false) String endTime) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {

            Date startTimeDate = null;
            if (startTime != null && !startTime.equalsIgnoreCase("")) {
                try {
                    startTimeDate = DateUtil.getDateFromStr(startTime);
                } catch (Exception e) {
                    startTimeDate = DateUtil.getDateFromStr("2017-05-01");
                }
            } else {
                startTimeDate = DateUtil.getDateFromStr("2017-05-01");
            }
            Date endTimeDate = null;
            if (endTime != null && !endTime.equalsIgnoreCase("")) {
                endTimeDate = DateUtil.getDateFromStr(endTime);
            } else {
                endTimeDate = new Date();
            }

            int number = 0;
            if (brandId == 0) {
                number = userCoinBusiness.findFullNameByStatus(status, startTimeDate, endTimeDate);
            } else {
                number = userCoinBusiness.findFullNameByStatus(brandId, status, startTimeDate, endTimeDate);
            }

            if (number == 0) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                map.put(CommonConstants.RESP_MESSAGE, "查询成功，无相关数据");
                map.put(CommonConstants.RESULT, 0);
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                map.put(CommonConstants.RESP_MESSAGE, "查询成功");
                map.put(CommonConstants.RESULT, number);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "查询失败");
        }
        return map;
    }

}
